package com.wiz.web.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wiz.common.ResponseCode;
import com.wiz.common.util.DateUtil;
import com.wiz.common.util.DecimalUtil;
import com.wiz.common.util.MemberPermissionUtil;
import com.wiz.web.dao.mapper.AccountMapper;
import com.wiz.web.dao.mapper.AuthorityMapper;
import com.wiz.web.dao.mapper.FuellingMapper;
import com.wiz.web.dao.mapper.HqStationMapper;
import com.wiz.web.dao.mapper.MemberMapper;
import com.wiz.web.exception.FuellingOrderException;
import com.wiz.web.service.AccountService;
import com.wiz.web.vo.WxModelMessageVO;
import com.wiz.web.vo.criteria.AccountChargeHistoryCriteria;
import com.wiz.web.vo.criteria.AuthorityCriteria;
import com.wiz.web.vo.criteria.FuellingOrderCriteria;
import com.wiz.web.vo.criteria.HqStationCriteria;
import com.wiz.web.vo.criteria.MemberCriteria;
import com.wiz.web.vo.to.AccountAmountHistoryTO;
import com.wiz.web.vo.to.AccountChargeHistoryTO;
import com.wiz.web.vo.to.AccountPointHistoryTO;
import com.wiz.web.vo.to.AuthorityTO;
import com.wiz.web.vo.to.FuellingPayOrderTO;
import com.wiz.web.vo.to.MemberGradeTO;
import com.wiz.web.vo.to.MemberTO;
import com.wiz.web.vo.to.PRConfigTO;
import com.wiz.web.vo.to.PointTO;
import com.wiz.web.vo.type.AmountHistoryType;
import com.wiz.web.vo.type.CompanyType;
import com.wiz.web.vo.type.MemberOperationType;
import com.wiz.web.vo.type.PayChannelType;
import com.wiz.web.vo.type.PayStatusType;
import com.wiz.web.vo.type.PointHistoryType;

@Service("accountService")
public class AccountServiceImpl implements AccountService,ResponseCode {
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	@Resource
	private MemberMapper memberMapper;
	@Resource
	private AuthorityMapper authorityMapper;
	@Resource
	private AccountMapper accountMapper;
	@Resource
	private FuellingMapper fuellingMapper;
	@Resource
	private HqStationMapper hqStationMapper;
	
	
	/**
	 * 获取会员等级相应的优惠价格
	 * @param memberId
	 * @return
	 */
	private MemberGradeTO getGradeByMemberId(String memberId){
		MemberCriteria criteria = new MemberCriteria();
		criteria.setMemberId(memberId);
		return memberMapper.getGradeByMemberId(criteria);
	}
	
	
	/**
	 * -------------------------------------------  订单处理阶段  -----------------------------------------------------------
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation = Isolation.REPEATABLE_READ)
	public WxModelMessageVO handlerOrder(FuellingOrderCriteria criteria) throws Exception {//只要进了此方法即会发生扣余额行为,金额以客户端为标准
		FuellingPayOrderTO orderTO = fuellingMapper.getFuellingPayOrderTO(criteria);
		if(orderTO.getCalculStatus() == 1){
			log.info("order ="+orderTO.getFuellingOrderId()+"has calculed");
			return null;
		}
		WxModelMessageVO vo = new WxModelMessageVO();
		vo.setHqId(orderTO.getHqId());
		vo.setHqName(orderTO.getHqName());
		vo.setStationName(orderTO.getStationName());
		vo.setPaidTypeName(orderTO.getPaidTypeName());
		vo.setCreatedTime(orderTO.getCreatedTime());
		if(orderTO.getPayStatus().intValue() == PayStatusType.PAID.getId()
				&& orderTO.getPaidTypeId().intValue() == PayChannelType.BALANCE.getId()
				&& StringUtils.isNotBlank(orderTO.getMemberId())){//余额支付 已支付状态,需参与计算
			payBalanceOrder(orderTO,vo);
		}else if(orderTO.getPayStatus().intValue() == PayStatusType.PAID.getId()){//已支付状态，非余额支付处理
			payNotBalanceOrder(orderTO,vo);
		}
		return vo;
	}
	
	/**
	 * 余额支付订单
	 * @param orderTO
	 * @throws Exception
	 */
	private void payBalanceOrder(FuellingPayOrderTO orderTO,WxModelMessageVO vo) throws Exception {//只要进了此方法即会发生扣余额行为,金额出错，以客户端为标准
		String authorityType = orderTO.getAuthorityType();
		if(authorityType.equals("S")){//服务器授权
			payOrderWithAuthority(orderTO,vo);
		}else{
			payOrderWithBalancePay(orderTO,vo);
		}
	}
	
	/**
	 * 带服务器授权的余额支付
	 * @param orderTO
	 */
	private void payOrderWithAuthority(FuellingPayOrderTO orderTO,WxModelMessageVO vo){
		MemberCriteria memberCriteria = new MemberCriteria();
		memberCriteria.setMemberId(orderTO.getMemberId());
		memberCriteria.setHqId(orderTO.getHqId());
		MemberTO memberTO = memberMapper.getMemberAmountInfo(memberCriteria);//使用用户
		MemberTO accountMemberTO = null;//支付用户
		if(memberTO.getCompanyType() == CompanyType.GENERAL_PAY.getId()){//总帐支付
			memberCriteria.setMemberId(memberTO.getMemberAccountId());
			accountMemberTO = memberMapper.getMemberAmountInfo(memberCriteria);
		}else{
			accountMemberTO = memberTO;
		}
		AuthorityCriteria authorityCriteria = new AuthorityCriteria();
		authorityCriteria.setAuthorityId(orderTO.getAuthorityId());
		List<AuthorityTO> list = authorityMapper.getFuellingAutorityTO(authorityCriteria);
		AuthorityTO authorityTO = list.get(0);
		if(authorityTO.getStatus() != 0){//
			//授权状态有误,不解冻金额
			log.error("FuellingAuthority status error in payOrder,ID="+authorityTO.getAuthorityId()+",status="+authorityTO.getStatus());
		}else{
			//解冻金额
			accountMapper.subFrozenAmount(authorityTO.getMemberAccountId(), authorityTO.getMemberFrozenAmount());
		}
		authorityCriteria.setStatus(2);
		//更新权限状态
		authorityMapper.updateFuellingAuthorityByCriteria(authorityCriteria);
		//异常记录
		if(orderTO.getReceivableAmount() > authorityTO.getMemberFrozenAmount()){
			log.error("orderTO="+orderTO.getFuellingOrderId()+"payOrderWithAuthority , ReceivableAmount greater than MemberFrozenAmount");
		}
		//实收金额
		double realincomeAmount = orderTO.getRealincomeAmount();
		//积分计算
		Double point = DecimalUtil.multi0((double)authorityTO.getAmountPoint(), Math.floor(realincomeAmount));
		
		insertAmountHistory(AmountHistoryType.FUL.getId(),AmountHistoryType.FUL.getName(),
				orderTO.getFuellingOrderId(),PointHistoryType.SUB.getId(),realincomeAmount,accountMemberTO,authorityTO);
		accountMapper.updateTotalPaidByMember(accountMemberTO.getMemberId(), realincomeAmount);
		updateAmountLimitHistory(memberTO,accountMemberTO,realincomeAmount);
		
		vo.setAmount(String.valueOf(realincomeAmount));
		vo.setVol(orderTO.getVol().toString());
		vo.setPRName(orderTO.getPrName());
		vo.setDiscountAmount(orderTO.getDiscountAmount().toString());
		vo.setRealincomeAmount(orderTO.getRealincomeAmount().toString());
		vo.setStationId(orderTO.getStationId());
		vo.setPhoneNum(memberTO.getPhoneNum());
		
		if(point.intValue()>0){
			accountMapper.addPoint(accountMemberTO.getMemberId(), point);
			insertPointHistory(orderTO, accountMemberTO, point.intValue());//注意精度是否丢失
		}
		if(memberTO.getCompanyType() == CompanyType.GENERAL_PAY.getId()){//总帐支付情况不会向使用帐户发送信息
			vo.setBalanceAmount(String.valueOf(memberTO.getAmount()));
			vo.setPoint("0");
			vo.setBalancePoint(String.valueOf(memberTO.getPoint()));
		}else{
			vo.setBalanceAmount(String.valueOf(DecimalUtil.sub(accountMemberTO.getAmount(),realincomeAmount)));
			vo.setPoint(String.valueOf(point.intValue()));
			vo.setBalancePoint(String.valueOf(accountMemberTO.getPoint()+point.intValue()));
		}
		//更新计算状态
		int calStatus = fuellingMapper.determineCalculStatus(orderTO.getFuellingOrderId());
		if(calStatus < 1){
			throw new FuellingOrderException(orderTO.getFuellingOrderId(),"payOrderWithAuthority CalculStatus has changed",3);
		}
	}
	
	/**
	 * 客户端授权余额支付后续处理
	 * @param orderTO
	 */
	private void payOrderWithBalancePay(FuellingPayOrderTO orderTO,WxModelMessageVO vo){//余额支付
		MemberCriteria memberCriteria = new MemberCriteria();
		memberCriteria.setMemberId(orderTO.getMemberId());
		memberCriteria.setHqId(orderTO.getHqId());
		MemberTO memberTO = memberMapper.getMemberAmountInfo(memberCriteria);
		MemberTO accountMemberTO = null;
		if(memberTO.getCompanyType() == CompanyType.GENERAL_PAY.getId()){//总帐支付
			memberCriteria.setMemberId(memberTO.getMemberAccountId());
			accountMemberTO = memberMapper.getMemberAmountInfo(memberCriteria);
		}else{
			accountMemberTO = memberTO;
		}
		
		MemberGradeTO gradeTO = getGradeByMemberId(accountMemberTO.getMemberId());
		PRConfigTO prTO = hqStationMapper.getPrConfig(orderTO.getPrId());
		double amountPoint = 0.00;
		if(prTO != null && gradeTO != null){
			if(prTO.getOilType() == 2){//柴油优惠
				amountPoint = gradeTO.getPoint();//暂时使用汽油积分政策
			}else{
				amountPoint = gradeTO.getPoint();
			}
		}
		//应收金额
		double realincomeAmount = orderTO.getRealincomeAmount();
		//积分计算
		Double point = DecimalUtil.multi0(amountPoint, Math.floor(realincomeAmount));
		
		vo.setVol(orderTO.getVol().toString());
		vo.setPRName(orderTO.getPrName());
		vo.setDiscountAmount(orderTO.getDiscountAmount().toString());
		vo.setRealincomeAmount(orderTO.getRealincomeAmount().toString());
		vo.setPhoneNum(memberTO.getPhoneNum());
		vo.setAmount(String.valueOf(realincomeAmount));
		vo.setStationId(orderTO.getStationId());
		
		if(point.intValue()>0){
			accountMapper.addPoint(accountMemberTO.getMemberId(), point);
			insertPointHistory(orderTO, accountMemberTO, point.intValue());//注意精度是否丢失
		}
		if(memberTO.getCompanyType() == CompanyType.GENERAL_PAY.getId()){//总帐支付情况不会向使用帐户发送信息
			vo.setBalanceAmount(String.valueOf(memberTO.getAmount()));
			vo.setPoint("0");
			vo.setBalancePoint(String.valueOf(memberTO.getPoint()));
		}else{
			vo.setBalanceAmount(String.valueOf(DecimalUtil.sub(accountMemberTO.getAmount(),realincomeAmount)));
			vo.setPoint(String.valueOf(point.intValue()));
			vo.setBalancePoint(String.valueOf(accountMemberTO.getPoint()+point.intValue()));
		}
		//更新计算状态
		int calStatus = fuellingMapper.determineCalculStatus(orderTO.getFuellingOrderId());
		if(calStatus < 1){
			throw new FuellingOrderException(orderTO.getFuellingOrderId(),"payOrderWithoutAuthority CalculStatus has changed",3);
		}
	}
	
	/**
	 * 非余额支付订单，目前只做了积分操作
	 * @param orderTO
	 * @throws Exception
	 */
	private void payNotBalanceOrder(FuellingPayOrderTO orderTO,WxModelMessageVO vo) throws Exception{
		if(StringUtils.isNotBlank(orderTO.getMemberId())){
			MemberCriteria memberCriteria = new MemberCriteria();
			memberCriteria.setMemberId(orderTO.getMemberId());
			memberCriteria.setHqId(orderTO.getHqId());
			MemberTO memberTO = memberMapper.getMemberAmountInfo(memberCriteria);
			if(memberTO.getMemberId().equals(memberTO.getMemberAccountId())){//使用帐户与付款账户相同才进行积分
				MemberGradeTO gradeTO = getGradeByMemberId(orderTO.getMemberId());
				if(gradeTO != null){
					PRConfigTO prTO = hqStationMapper.getPrConfig(orderTO.getPrId());
					double amountPoint = 0.00;
					if(prTO != null){
						if(prTO.getOilType() == 2){//柴油优惠
							amountPoint = gradeTO.getPoint();//暂时使用汽油积分政策
						}else{
							amountPoint = gradeTO.getPoint();
						}
					}
					Double point = DecimalUtil.multi0(amountPoint, Math.floor(orderTO.getRealincomeAmount()));
					if(point.intValue()>0){
						accountMapper.addPoint(orderTO.getMemberId(), point);
						insertPointHistory(orderTO, memberTO, point.intValue());//注意精度是否丢失
					}
					vo.setPoint(String.valueOf(point.intValue()));
					vo.setBalancePoint(String.valueOf(memberTO.getPoint()+point.intValue()));
				}else{
					vo.setPoint("0");
					vo.setBalancePoint(String.valueOf(memberTO.getPoint()));
				}
				vo.setVol(orderTO.getVol().toString());
				vo.setPRName(orderTO.getPrName());
				vo.setDiscountAmount(orderTO.getDiscountAmount().toString());
				vo.setRealincomeAmount(orderTO.getRealincomeAmount().toString());
				vo.setPhoneNum(memberTO.getPhoneNum());
				vo.setAmount(String.valueOf(orderTO.getRealincomeAmount()));
				vo.setBalanceAmount(String.valueOf(memberTO.getAmount()));
				vo.setStationId(orderTO.getStationId());
			}
		}
		//更新计算状态
		int calStatus = fuellingMapper.determineCalculStatus(orderTO.getFuellingOrderId());
		if(calStatus < 1){
			throw new FuellingOrderException(orderTO.getFuellingOrderId(),"payNotBalanceOrder CalculStatus has changed",3);
		}
	}
	
	/**
	 * 新增积分流水
	 * @param orderTO
	 * @param memberTO
	 * @param point
	 */
	private void insertPointHistory(FuellingPayOrderTO orderTO,MemberTO memberTO,int point){
		AccountPointHistoryTO to = new AccountPointHistoryTO();
		to.setMemberId(memberTO.getMemberId());
		to.setMemberName(memberTO.getMemberName());
		to.setCompanyId(memberTO.getCompanyId());
		to.setCompanyName(memberTO.getCompanyName());
		to.setHqId(memberTO.getHqId());
		to.setStationId(orderTO.getStationId());
		to.setPoint(point);
		to.setBalancePoint(memberTO.getPoint()+point);
		to.setPointType(PointHistoryType.ADD.getId());
		to.setRefId(orderTO.getFuellingOrderId());
		accountMapper.addPointHistory(to);
	}
	
	/**
	 * 更新用户金额限制流水
	 * @param memberId
	 * @param costAmount 消费金额
	 */
	private void updateAmountLimitHistory(MemberTO memberTO,MemberTO accountMemberTO,double costAmount){
		accountMapper.updateAmountLimitHistoryByMember(accountMemberTO.getMemberId(), costAmount);
		if(memberTO.getCompanyType() == CompanyType.GENERAL_PAY.getId()){//总帐支付需更新使用授权人的总额限制
			accountMapper.updateAmountLimitHistoryByMember(memberTO.getMemberId(), costAmount);
		}
	}
	
	/**
	 * -------------------------------------------  余额支付阶段  -----------------------------------------------------------
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation = Isolation.REPEATABLE_READ)
	public String balancePay(int amountType,String amountTypeName,String refId,
			double amount,String memberId,String hqId) throws Exception{
		MemberCriteria memberCriteria = new MemberCriteria();
		memberCriteria.setMemberId(memberId);
		memberCriteria.setHqId(hqId);
		MemberTO memberTO = memberMapper.getMemberAmountInfo(memberCriteria);
		if(memberTO == null || memberTO.getStatus() != 1){
			return RESPONSE_CODE_INVALID_MEMBER;
		}
		MemberTO accountMemberTO = null;
		if(memberTO.getCompanyType() == CompanyType.GENERAL_PAY.getId()){//总帐支付
			memberCriteria.setMemberId(memberTO.getMemberAccountId());
			accountMemberTO = memberMapper.getMemberAmountInfo(memberCriteria);
		}else{
			accountMemberTO = memberTO;
		}
		if(accountMemberTO == null || accountMemberTO.getStatus() != 1){
			return RESPONSE_CODE_INVALID_MEMBER;
		}
		if(accountMemberTO.getAmount() - accountMemberTO.getFrozenAmount() < amount){
			return RESPONSE_CODE_NOT_ENOUGH_AMOUNT;
		}
		insertAmountHistory(amountType,amountTypeName,refId,
				PointHistoryType.SUB.getId(),amount,accountMemberTO,null);
		accountMapper.updateTotalPaidByMember(accountMemberTO.getMemberId(), amount);
		updateAmountLimitHistory(memberTO,accountMemberTO,amount);
		return RESPONSE_CODE_OK;
	}
	
	/**
	 * -------------------------------------------  积分兑换阶段  -----------------------------------------------------------
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation = Isolation.DEFAULT)
	public WxModelMessageVO exchangePoint(HqStationCriteria criteria) throws Exception{
		MemberCriteria memberCriteria = new MemberCriteria();
		memberCriteria.setMemberId(criteria.getMemberId());
		memberCriteria.setHqId(criteria.getHqId());
		MemberTO memberTO = memberMapper.getMemberAmountInfo(memberCriteria);//获取积分信息
		if(memberTO == null || memberTO.getStatus() != 1){
			return null;
		}
		boolean b = MemberPermissionUtil.check(MemberOperationType.EXCHANGE.getId(), memberTO.getStatus());
		if(!b){
			return null;
		}
		WxModelMessageVO vo = new WxModelMessageVO();
		vo.setHqId(memberTO.getHqId());
		vo.setHqName(memberTO.getHqName());
		vo.setStationName(criteria.getStationName());
		int totalPoint = memberTO.getPoint();//总积分
		int totalCost = 0;//总消费
		for(PointTO pointCriteria:criteria.getPointList()){
			PointTO pointTO = hqStationMapper.getPointByConfigId(pointCriteria.getId());
			if(pointTO == null){
				throw new Exception("兑换礼品已下线");
			}
			int costPoint = pointTO.getPointNeedNum() * pointCriteria.getPointConfigNum();//单条兑换所需总分
			if(totalPoint >= costPoint){
				int result = accountMapper.subPoint(criteria.getMemberId(), costPoint);
				if(result>0){
					AccountPointHistoryTO to = new AccountPointHistoryTO();
					to.setMemberId(memberTO.getMemberId());
					to.setMemberName(memberTO.getMemberName());
					to.setCompanyId(memberTO.getCompanyId());
					to.setCompanyName(memberTO.getCompanyName());
					to.setPoint(costPoint*-1);
					to.setBalancePoint(totalPoint-costPoint);
					to.setRefId(String.valueOf(pointTO.getId()));
					to.setStationId(criteria.getStationId());
					to.setStationName(criteria.getStationName());
					to.setStationAdminId(criteria.getStationAdminId());
					to.setStationAdminName(criteria.getStationAdminName());
					to.setHqId(pointTO.getHqId());
					to.setPointType(PointHistoryType.SUB.getId());
					to.setMemo("兑换"+pointTO.getPointName()+"*"+pointCriteria.getPointConfigNum());
					accountMapper.addPointHistory(to);
				}
			}else{
				throw new Exception("积分不足");
			}
			totalPoint-=costPoint;
			totalCost+=costPoint;
		}
		vo.setBalancePoint(String.valueOf(totalPoint));
		vo.setPoint(String.valueOf(totalCost));
		vo.setCreatedTime(DateUtil.formatDateTime(new Date()));
		return vo;
	}
	
	
	
	/**
	 * -------------------------------------------  充值阶段  -----------------------------------------------------------
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation = Isolation.REPEATABLE_READ)
	public AccountChargeHistoryTO chargeAmountByClient(AccountChargeHistoryCriteria chargeCriteria) throws Exception{
		chargeCriteria.setSourceChargeType(2);
		Double chargeAmount = chargeCriteria.getAmount();
		Double giftAmount = chargeCriteria.getGiftAmount();//赠送金额
		MemberCriteria memberCriteria = new MemberCriteria();
		memberCriteria.setMemberId(chargeCriteria.getMemberId());
		memberCriteria.setHqId(chargeCriteria.getHqId());
		MemberTO memberTO = memberMapper.getMemberAmountInfo(memberCriteria);
		if(memberTO == null){
			return null;
		}
		boolean b = MemberPermissionUtil.check(MemberOperationType.CHARGE.getId(), memberTO.getStatus());
		if(!b){
			return null;
		}
		if(memberTO.getIsAllCha() != 1 && !memberTO.getChaStations().contains(chargeCriteria.getStationId())){
			return null;
		}
		MemberTO accountMemberTO = null;
		if(memberTO.getCompanyType() == CompanyType.GENERAL_PAY.getId()){//总帐
			memberCriteria.setMemberId(memberTO.getMemberAccountId());
			accountMemberTO = memberMapper.getMemberAmountInfo(memberCriteria);
		}else{
			accountMemberTO = memberTO;
		}
		b = MemberPermissionUtil.check(MemberOperationType.CHARGE.getId(), accountMemberTO.getStatus());
		if(!b){
			return null;
		}
		chargeCriteria.setMemberName(accountMemberTO.getMemberName());
		chargeCriteria.setMemberCardNo(accountMemberTO.getCardNo());
		chargeCriteria.setMemberPhoneNum(accountMemberTO.getPhoneNum());
		chargeCriteria.setMemberType(accountMemberTO.getMemberType());
		chargeCriteria.setMemberLicensePlate(accountMemberTO.getLicensePlate());
		chargeCriteria.setCompanyId(accountMemberTO.getCompanyId());
		chargeCriteria.setCompanyName(accountMemberTO.getCompanyName());
		accountMapper.addChargeHistory(chargeCriteria);//新增充值流水
		Double totalAmount = DecimalUtil.add(chargeAmount,giftAmount);
		insertAmountHistory(AmountHistoryType.CHA.getId(),AmountHistoryType.CHA.getName(),
				String.valueOf(chargeCriteria.getId()),PointHistoryType.ADD.getId(),totalAmount,accountMemberTO,null);
		accountMapper.updateTotalChargeyByMember(accountMemberTO.getMemberId(), chargeAmount);
		AccountChargeHistoryTO chargeTO = memberMapper.getMemberChargeHistroyById(chargeCriteria.getId());
		chargeTO.setMemberBlanceAmount(DecimalUtil.add(accountMemberTO.getAmount(),totalAmount));
		return chargeTO;
	}
	
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation = Isolation.REPEATABLE_READ)
	public AccountChargeHistoryTO chargeAmountByWx(String hqId, String openId, Double chargeAmount,
			String refId) throws Exception{
		Double giftAmount = 0.00;//赠送金额
		MemberCriteria memberCriteria = new MemberCriteria();
		memberCriteria.setOpenId(openId);
		memberCriteria.setHqId(hqId);
		MemberTO memberTO = memberMapper.getMemberAmountInfo(memberCriteria);
		MemberTO accountMemberTO = null;
		if(memberTO.getCompanyType() == CompanyType.GENERAL_PAY.getId()){//总帐
			memberCriteria.setMemberId(memberTO.getMemberAccountId());
			accountMemberTO = memberMapper.getMemberAmountInfo(memberCriteria);
		}else{
			accountMemberTO = memberTO;
		}
		AccountChargeHistoryCriteria chargeCriteria = new AccountChargeHistoryCriteria();
		chargeCriteria.setAmount(chargeAmount);
		chargeCriteria.setGiftAmount(giftAmount);
		chargeCriteria.setSourceChargeType(3);
		chargeCriteria.setMemberId(accountMemberTO.getMemberId());
		chargeCriteria.setMemberName(accountMemberTO.getMemberName());
		chargeCriteria.setMemberCardNo(accountMemberTO.getCardNo());
		chargeCriteria.setMemberPhoneNum(accountMemberTO.getPhoneNum());
		chargeCriteria.setMemberType(accountMemberTO.getMemberType());
		chargeCriteria.setMemberLicensePlate(accountMemberTO.getLicensePlate());
		chargeCriteria.setCompanyId(accountMemberTO.getCompanyId());
		chargeCriteria.setCompanyName(accountMemberTO.getCompanyName());
		chargeCriteria.setHqId(accountMemberTO.getHqId());
		chargeCriteria.setHqName(accountMemberTO.getHqName());
		chargeCriteria.setStationId(accountMemberTO.getStationId());
		chargeCriteria.setStationName(accountMemberTO.getStationName());
		chargeCriteria.setPaidTypeId(PayChannelType.WEIXIN.getId());
		chargeCriteria.setPaidTypeName(PayChannelType.WEIXIN.getName());
		chargeCriteria.setMemo("微信充值");
		chargeCriteria.setRefId(refId);
		accountMapper.addChargeHistory(chargeCriteria);//新增充值流水
		Double totalAmount = DecimalUtil.add(chargeAmount,giftAmount);
		insertAmountHistory(AmountHistoryType.CHA.getId(),AmountHistoryType.CHA.getName(),
				String.valueOf(chargeCriteria.getId()),PointHistoryType.ADD.getId(),totalAmount,accountMemberTO,null);
		accountMapper.updateTotalChargeyByMember(accountMemberTO.getMemberId(), chargeAmount);
		AccountChargeHistoryTO chargeTO = memberMapper.getMemberChargeHistroyById(chargeCriteria.getId());
		chargeTO.setMemberBlanceAmount(DecimalUtil.add(accountMemberTO.getAmount(),totalAmount));
		return chargeTO;
	}
	
	/**
	 * 资金发生变动后，增减金额与增加流水
	 */
	private void insertAmountHistory(int amountType,String amountTypeName,
			String refId,int addReduce,double amount,MemberTO memberTO,AuthorityTO authorityTO){
		AccountAmountHistoryTO to = new AccountAmountHistoryTO();
		if(addReduce == PointHistoryType.ADD.getId()){//增加金额
			accountMapper.addAmount(memberTO.getMemberId(), amount);
			to.setBalanceAmount(DecimalUtil.add(memberTO.getAmount(),amount));
			to.setAmount(amount);
		}else if(addReduce == PointHistoryType.SUB.getId()){//减少金额
			accountMapper.subAmount(memberTO.getMemberId(), amount);
			to.setBalanceAmount(DecimalUtil.sub(memberTO.getAmount(),amount));
			to.setAmount(DecimalUtil.multi2(amount, -1.00));
		}
		if(authorityTO!=null){
			to.setFrozenAmount(authorityTO.getMemberFrozenAmount());
			to.setBalanceFrozenAmount(DecimalUtil.sub(memberTO.getFrozenAmount(),authorityTO.getMemberFrozenAmount()));
		}else{
			to.setFrozenAmount(0.00);
			to.setBalanceFrozenAmount(memberTO.getFrozenAmount());
		}
		to.setAmountType(amountType);
		to.setAmountTypeName(amountTypeName);
		to.setMemberId(memberTO.getMemberId());
		to.setMemberName(memberTO.getMemberName());
		to.setCompanyId(memberTO.getCompanyId());
		to.setCompanyName(memberTO.getCompanyName());
		to.setRefId(refId);
		accountMapper.addAmountHistory(to);
	}
}
